package com.lby.psychology.config;

import com.lby.psychology.model.QQAccessToken;
import com.lby.psychology.model.QQOpenId;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;


import java.io.IOException;

@Slf4j
public class QQAuthenticationFilter extends AbstractAuthenticationProcessingFilter {



    private final QQLoginConfig qqLoginConfig;

    private final RestTemplate restTemplate;

    public QQAuthenticationFilter(String defaultFilterProcessesUrl,RestTemplate restTemplate, QQLoginConfig qqLoginConfig) {
        super(new AntPathRequestMatcher(defaultFilterProcessesUrl,"GET"));
        this.restTemplate = restTemplate;
        this.qqLoginConfig = qqLoginConfig;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws AuthenticationException, IOException, ServletException {
        // 回调地址为get  ，直接获取返回得code
        String code = httpServletRequest.getParameter(qqLoginConfig.CODE);

        String accessTokenUrl = qqLoginConfig.getAccessTokenUrl(code);

        QQAccessToken qqAccessToken = restTemplate.getForObject(accessTokenUrl, QQAccessToken.class);

        UsernamePasswordAuthenticationToken authenticationToken = null;
        if(!ObjectUtils.isEmpty(qqAccessToken)){
            //获取openId
            QQOpenId qqOpenId = restTemplate.getForObject(qqLoginConfig.getOpenIdUrl(qqAccessToken.getAccess_token()), QQOpenId.class);

            if(!ObjectUtils.isEmpty(qqOpenId)) {
                log.info("获取到得openId :{}", qqOpenId.getOpenid());
                // 将 accessToken 作为密码,openId 作为用户名
                authenticationToken = new UsernamePasswordAuthenticationToken(qqOpenId, qqAccessToken);
            }
        }
        return this.getAuthenticationManager().authenticate(authenticationToken);
    }

}
